package blog.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import blog.entity.User;
import blog.mapper.ArticleMapper;
import blog.mapper.UserMapper;
import blog.service.ArticleService;
import blog.service.UserService;

/**
 * 用户服务层
 * @author 江佳洋
 *
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ArticleMapper articleMapper;
	
	@Autowired
	private ArticleService articleService;
	/**
	 * 根据用户名或者邮箱得到用户信息
	 */
	public User getUserByNameOrEmail(String str) {
		return userMapper.getUserByNameOrEmail(str);
	}
	
	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(User user) {
		userMapper.addUser(user);
	}

	/**
	 * 查询所有用户
	 * @return
	 */
	public List<User> getUserList() {
		List<User> userList = userMapper.getUserList();
		for(User user:userList) {
			Integer articleCount = articleMapper.getUserArticleCountById(user.getUserId());
			user.setArticleCount(articleCount);
		}
		return userList;
	}

	/**
	 * 根据id查询用户
	 * @param userId
	 * @return
	 */
	public User getUserById(Integer userId) {
		return userMapper.getUserById(userId);
	}

	/**
	 * 修改用户信息
	 * @param user
	 */
	public void editUser(User user) {
		userMapper.editUser(user);
		
	}

	/**
	 * 根据id删除用户
	 * @param userId
	 */
	public void deleteUser(Integer userId) {
		userMapper.deleteUser(userId);
		//查询出该用户所拥有的文章id  然后删除
		List<Integer> list = articleMapper.getArticleByUserId(userId);
		for(Integer id:list) {
			articleService.deleteArticleById(id);
		}
	}

}
